package com.android.corestat.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DesEncryption {
	private final static String KEY = "instools";
	private final static String DES = "DES";
	private final static String ENCODE = "UTF-8";
	/**文件加密解密的key*/  
    private Key fileKey;
    /**文件密钥*/  
    private static Cipher fileCipher;  
    public DesEncryption() throws Exception  
    {  
        initKey(KEY);  
        initCipher();  
    }  
      
    /** 
     * 创建一个加密解密的key 
     * @param keyRule  
     */  
    private void initKey(String keyRule) {  
        byte[] keyByte = keyRule.getBytes();  
        // 创建一个空的八位数组,默认情况下为0   
        byte[] byteTemp = new byte[8];  
        // 将用户指定的规则转换成八位数组   
        for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {  
            byteTemp[i] = keyByte[i];  
        }  
        fileKey = new SecretKeySpec(byteTemp, DES);  
    }
     
    /**
     * Description 根据键值进行加密
     * @param data 
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    public static String encryptString(String data) throws Exception {
        byte[] bt = encryptByte(data.getBytes(ENCODE), KEY.getBytes(ENCODE));
        String strs = new BASE64Encoder().encode(bt);
        return strs;
    }
 
    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decryptString(String data) throws
            Exception {
        if (data == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decryptByte(buf,KEY.getBytes(ENCODE));
        return new String(bt);
    }
 
    /**
     * Description 根据键值进行加密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] encryptByte(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
 
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
 
        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
 
        // Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance(DES);
 
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
 
        return cipher.doFinal(data);
    }
     
     
    /**
     * Description 根据键值进行解密
     * @param data
     * @param key  加密键byte数组
     * @return
     * @throws Exception
     */
    private static byte[] decryptByte(byte[] data, byte[] key) throws Exception {
        // 生成一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
 
        // 从原始密钥数据创建DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(key);
 
        // 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);
 
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance(DES);
 
        // 用密钥初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
 
        return cipher.doFinal(data);
    }
    
    /*** 
     * 初始化加载密码 
     * @throws Exception 
     */  
    private void initCipher() throws Exception  
    {  
        fileCipher = Cipher.getInstance(DES);  
        fileCipher.init(Cipher.ENCRYPT_MODE, fileKey);  
    }  
  
    /** 
     * 加密 
     *  
     * @param enfile 
     *            要加密的文件 
     * @param defile 
     *            加密后的文件 
     * @param key 
     *            密钥 
     * @throws Exception 
     */  
    public static void encryptFile(String enfile, String defile)  
            throws Exception {  
    	 byte[] key = KEY.getBytes();
        // 秘密（对称）密钥(SecretKey继承(key))  
        // 根据给定的字节数组构造一个密钥。  
        SecretKey deskey = new SecretKeySpec(key, DES);  
        // 生成一个实现指定转换的 Cipher 对象。Cipher对象实际完成加解密操作  
        Cipher c = Cipher.getInstance(DES);  
        // 用密钥初始化此 cipher  
        c.init(Cipher.ENCRYPT_MODE, deskey);  
  
        byte[] buffer = new byte[1024];  
        FileInputStream in = new FileInputStream(enfile);  
        OutputStream out = new FileOutputStream(defile);  
           
        CipherInputStream cin = new CipherInputStream(in, c);  
        int i;  
        while ((i = cin.read(buffer)) != -1) {  
            out.write(buffer, 0, i);  
        }  
        out.close();  
        cin.close();  
    }  
  
    /** 
     * 解密
     *  
     * @param enfile 
     *            加密的文件 
     * @param defile 
     *            解密密后的文件 
     * @param key 
     *            密钥 
     * @throws Exception 
     */  
    public static void decryptFile(String file, String defile)  
            throws Exception {  
    	byte[] key = KEY.getBytes();
        // DES算法要求有一个可信任的随机数源  
        SecureRandom sr = new SecureRandom();  
        // 创建一个 DESKeySpec 对象,指定一个 DES 密钥  
        DESKeySpec ks = new DESKeySpec(key);  
        // 生成指定秘密密钥算法的 SecretKeyFactory 对象。  
        SecretKeyFactory factroy = SecretKeyFactory.getInstance(DES);  
        // 根据提供的密钥规范（密钥材料）生成 SecretKey 对象,利用密钥工厂把DESKeySpec转换成一个SecretKey对象  
        SecretKey sk = factroy.generateSecret(ks);  
        // 生成一个实现指定转换的 Cipher 对象。Cipher对象实际完成加解密操作  
        Cipher c = Cipher.getInstance(DES);  
        // 用密钥和随机源初始化此 cipher  
        c.init(Cipher.DECRYPT_MODE, sk, sr);  
  
        byte[] buffer = new byte[1024];  
        FileInputStream in = new FileInputStream(file);  
        OutputStream out = new FileOutputStream(defile);  
        CipherOutputStream cout = new CipherOutputStream(out, c);  
        int i;  
        while ((i = in.read(buffer)) != -1) {  
            cout.write(buffer, 0, i);  
        }  
        cout.close();  
        in.close();  
    }
    
    public static void decryptFile(File file, File defile)  
            throws Exception {  
    	byte[] key = KEY.getBytes();
        // DES算法要求有一个可信任的随机数源  
        SecureRandom sr = new SecureRandom();  
        // 创建一个 DESKeySpec 对象,指定一个 DES 密钥  
        DESKeySpec ks = new DESKeySpec(key);  
        // 生成指定秘密密钥算法的 SecretKeyFactory 对象。  
        SecretKeyFactory factroy = SecretKeyFactory.getInstance(DES);  
        // 根据提供的密钥规范（密钥材料）生成 SecretKey 对象,利用密钥工厂把DESKeySpec转换成一个SecretKey对象  
        SecretKey sk = factroy.generateSecret(ks);  
        // 生成一个实现指定转换的 Cipher 对象。Cipher对象实际完成加解密操作  
        Cipher c = Cipher.getInstance(DES);  
        // 用密钥和随机源初始化此 cipher  
        c.init(Cipher.DECRYPT_MODE, sk, sr);  
  
        byte[] buffer = new byte[1024];  
        FileInputStream in = new FileInputStream(file);  
        OutputStream out = new FileOutputStream(defile);  
        CipherOutputStream cout = new CipherOutputStream(out, c);  
        int i;  
        while ((i = in.read(buffer)) != -1) {  
            cout.write(buffer, 0, i);  
        }  
        cout.close();  
        in.close();  
    }
    
    public static void decryptFile(InputStream in, OutputStream out)  
            throws Exception {  
    	byte[] key = KEY.getBytes();
        // DES算法要求有一个可信任的随机数源  
        SecureRandom sr = new SecureRandom();  
        // 创建一个 DESKeySpec 对象,指定一个 DES 密钥  
        DESKeySpec ks = new DESKeySpec(key);  
        // 生成指定秘密密钥算法的 SecretKeyFactory 对象。  
        SecretKeyFactory factroy = SecretKeyFactory.getInstance(DES);  
        // 根据提供的密钥规范（密钥材料）生成 SecretKey 对象,利用密钥工厂把DESKeySpec转换成一个SecretKey对象  
        SecretKey sk = factroy.generateSecret(ks);  
        // 生成一个实现指定转换的 Cipher 对象。Cipher对象实际完成加解密操作  
        Cipher c = Cipher.getInstance(DES);  
        // 用密钥和随机源初始化此 cipher  
        c.init(Cipher.DECRYPT_MODE, sk, sr);  
  
        byte[] buffer = new byte[1024];  
        CipherOutputStream cout = new CipherOutputStream(out, c);  
        int i;  
        while ((i = in.read(buffer)) != -1) {  
            cout.write(buffer, 0, i);  
        }  
        cout.close();  
        in.close();  
    }
}
